<?php
if( !defined('CORE') ) exit('Request Error!');
/**
 * 首页控制器
 *
 * @version 2020.11.05
 */
class ctl_yice_index
{
	public static $userinfo;
	public static $control;
	public $cache_enable = true;//缓存开关,调试时可设为false
	public $cachetime    = 7200;//缓存时间,秒(注意:内容页缓存是单独的在video_view中设置)
	public $cache_prefix = '';
	public $cache_key    = 'h5_index/index';
	public $str_where_ext = '`status`!=9';
	public $str_type = array(7=>"姻缘分析");
	public function __construct()
	{

	    $this->cache_prefix = $GLOBALS['config']['money']['smurl'];
		if (empty($this->items))
		{
			$this->items = new items();
		}
		tpl::assign('web_url',URL);
		//$pid = mod_topic::get_p_id();//获取一级栏目
		tpl::assign('pid',$pid);
		//获取广告
		//$this->getAd();
		$public_hand_data_cache = cache::get($this->cache_prefix,'public_hand_data');
		if($public_hand_data_cache==''){
			//$public_hand_data = mod_index::get_public_hand();//获取公用部分手动数据
			cache::set($this->cache_prefix,'public_hand_data',$public_hand_data,$this->cachetime); //写缓存
		}else{
			$public_hand_data = $public_hand_data_cache;//获取公用部分手动数据
		}
		tpl::assign('public_hand_data',$public_hand_data);
		if(isset($_SERVER['REQUEST_URI']) && false !== stripos($_SERVER['REQUEST_URI'],'clearcache')){
			$this->cache_enable = false;
		}
	}
//祈福点灯首页 MH
    public function index(){
        $username = req::item('username');
        $yuanwang = req::item('yuanwang');
		
		//替换特殊字符
		$yuanwang = str_ireplace('<','',$yuanwang);
		$yuanwang = str_ireplace('>','',$yuanwang);
		$yuanwang = str_ireplace("'",'',$yuanwang);
		
        $qfshow = req::item('qfshow');
        $lantern_id = req::item('lantern_id');
        /* $y = req::item('y');
        $m = req::item('m');
        $d = req::item('d');
        $h = req::item('h');
        $i = req::item('i');
        $cY = req::item('cY');
        $cM = req::item('cM');
        $cD = req::item('cD');
        $cH = req::item('cH'); */
        $term1 = req::item('term1');
        $term2 = req::item('term2');
        $start_term = req::item('start_term');
        $end_term = req::item('end_term');
        $start_term1 = req::item('start_term1');
        $end_term1 = req::item('end_term1');
        $lDate = req::item('lDate');
        $moneys = $GLOBALS['config']['money']['xydd'];
        tpl::assign('money',$moneys);
        //第四方支付
        $sys_pay_type=db::queryone("SELECT * FROM `system` WHERE `name` = 'pay_type'");
        tpl::assign('sys_pay_type',$sys_pay_type['config']);
        //include PATH_DATA.'/file_cache/xyd_data.php';
        $oid = req::item('oid');
        $token = req::item('token');
        
		//开始执行提交 MH20201103
		if($username!=''&& $yuanwang!=''){
            $oid = date('YmdGis') . rand(1000000000, 15000000000);
            $des = $username . '的祈福点灯';
           
			//$data = array('username' => $username, 'yuanwang' => $yuanwang, 'lantern_id' => $lantern_id, 'shen' => $shen, 'y' => $y, 'm' => $m, 'd' => $d, 'h' => $h, 'i' => $i, 'cY' => $cY, 'cM' => $cM, 'cD' => $cD, 'cH' => $cH, 'term1' => $term1, 'term2' => $term2, 'start_term' => $start_term, 'end_term' => $end_term, 'start_term1' => $start_term1, 'end_term1' => $end_term1, 'lDate' => $lDate);
			
            $datas = array('data' => '', 'oid' => $oid, 'createtime' => time(), 'type' => 21, 'qfdj' => '0', 'qfshow' => $qfshow, 'username' => $username, 'yuanwang' => $yuanwang, 'lantern_id' => $lantern_id, 'shen' => 0, 'ip' => util::get_client_ip(), 'des' => $des, 'money' => $moneys,'status' => 0);
            $cxoid = mod_order::get_order($oid);
            if ($cxoid['oid'] == "") {
                mod_order::add_order($datas);
            }
            mod_order::set_history($oid);
            //tpl::assign('xyd_data', $xyd_data[$lantern_id]);
            if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {//微信内
                $type = 'wechat';
            }else{
                $type = 'H5';
            }
            tpl::assign('oid', $oid);
            tpl::assign('type', $type);
            tpl::assign('token', base64_encode(md5($oid)));
            tpl::assign('des', $des);
            //tpl::assign('names', $data);
            $tpl = 'yice/xydd_orders.tpl';
        }elseif($oid!=''){
            if($token==base64_encode(md5($oid))){
				
                $row = mod_order::get_order($oid);
                if($row['status']!=1){
					//第二次准备付款					
					if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {//微信内
					    $type = 'wechat';
					}else{
					    $type = 'H5';
					}
					
					tpl::assign('type', $type);
                    tpl::assign('yz_pay',1);
                    tpl::assign('oid',$row['oid']);
                    tpl::assign('des',$row['des']);
                    tpl::assign('token', base64_encode(md5($oid)));
                    //tpl::assign('names',json_decode(urldecode($row['data']),true));
                    tpl::assign('xyd_data',$xyd_data['$lantern_id']);
                    $tpl     = 'yice/xydd_orders.tpl';
                }else{
                   // $row['data'] = json_decode(urldecode($row['data']),true);
                    $gf_start=date("Y.m.d",$row['createtime']);
                    $gf_end=date("Y.m.d",$row['createtime']+15552000);
                    tpl::assign('xyd_data',$xyd_data[$row['lantern_id']]);
                    if($row['xydd_img']==""){
                        $dst = "./statics/ffsm/xydd/images/qyd_find.png";
                        
						$img = db::queryone("select img from `yice_deng` where id='".$row['lantern_id']."' ");
						$src_path = $img['img'];
                        
						$xyddtext = $row['yuanwang'];
                        $xyddtext1 = '昵称：'.$row['username'].' '.$gf_start;
                        $xydd_img=$this-> xydd_img($dst,$src_path,$xyddtext,$xyddtext1);
                        mod_order::up_order(array('xydd_img'=>$xydd_img), " `oid`='".$oid."'");
                        tpl::assign('xydd_img','/xydd/'.$xydd_img);
                    }else{
                        tpl::assign('xydd_img','/xydd/'.$row['xydd_img']);
                    }
                    tpl::assign('data',$row);
                    tpl::assign('gf_start',$gf_start);
                    tpl::assign('gf_end',$gf_end);
                    $this->dl_js($row);
                    $tpl     = 'yice/xydd_find.tpl';
                }
            }else{
                die('验证失败!');
            }
        }else{
            if($lantern_id!=''){
				
				$deng = db::queryone("select img,img_icon,title,dengci1,dengci2 from `yice_deng` where id='".$lantern_id."' ORDER BY `id` DESC");
				$lantern_title=$deng['title'].'['.$deng['dengci1'].','.$deng['dengci2'].']';
                $lantern_img = $deng['img'];
				$lantern_imgicon = $deng['img_icon'];
				
				tpl::assign('xyd_data',$xyd_data[$lantern_id]);
				tpl::assign('lantern_title',$lantern_title);
				tpl::assign('lantern_imgicon',$lantern_imgicon);
				tpl::assign('lantern_img',$lantern_img);
                tpl::assign('lantern_id',$lantern_id);
                $tpl     = 'yice/xydd_order.tpl';
            }else{
				
                $page = req::item('page');
                $list_cl = req::item('list_cl');
                $week = req::item('week');
                if($page>1){
					
                    $page_s=20*($page-1);
                    $page_e=20*$page;
                    if($list_cl=="week"){
                        $xydd_all=db::fetch_all(db::query('SELECT * FROM `ffsm_orders` WHERE week(from_unixtime(`createtime`))=week(now())   and YEAR(from_unixtime(`createtime`))=YEAR(now()) and `shen` = 1 AND `type` = 21 AND `qfshow` = 1 ORDER BY `qfdj` DESC limit '.$page_s.','.$page_e));
						
                    }else if($list_cl=="zd"){
                        $xydd_all=db::fetch_all(db::query('SELECT * FROM `ffsm_orders` WHERE `shen` = 1 AND `type` = 21 AND `qfshow` = 1 ORDER BY `qfdj` DESC limit '.$page_s.','.$page_e));
                    }else{
                        $xydd_all=db::fetch_all(db::query('SELECT * FROM `ffsm_orders` WHERE `shen` = 1 AND `type` = 21 AND `qfshow` = 1 ORDER BY `id` DESC limit '.$page_s.','.$page_e));
                    }
					
					foreach($xydd_all as $k=>$v){
						$img = db::queryone("select img from `yice_deng` where id='".$v['lantern_id']."' ORDER BY `id` DESC");
						$xydd_all[$k]['lantern_img'] = $img['img'];
					}
					
                    if(!empty($xydd_all)){
                        tpl::assign('xydd_all',$xydd_all);
                    }
                    $tpl     = 'yice/xydd_page.tpl';
                }else{
					
					//所有灯
					$deng_all=db::fetch_all(db::query('SELECT * FROM `yice_deng` WHERE `status` = 1 ORDER BY `paixu` DESC'));
					tpl::assign('deng_all',$deng_all);
					
                    $tpl     = 'yice/xydd.tpl';
                }
            }
        }
        $content = tpl::fetch($tpl);
        exit($content);
    }
	
	public function xydd_dj(){
			$id = req::item('id');
			$xydd_ck = $_COOKIE["xydd_".$id];
			if($xydd_ck>0){
				//echo "<script> alert('已经祝福了！祝愿您的心愿早日达成！') </script>";
				//header('location:/?ac=index');
				tpl::assign('info',"已经祝福了！祝愿您的心愿早日达成！");	
			}else{
				db::query('UPDATE `ffsm_orders` SET `qfdj` = `qfdj`+1 WHERE `id` = '.$id);
	         	
				
				
				tpl::assign('isdj',1);
				tpl::assign('info',"感谢您的祝福！也祝愿您的心愿早日达成！");
				$expire=time()+60*60*12;
				setcookie("xydd_".$id, $id, $expire,'/');
				
				//echo "<script> alert('感谢您的祝福！也祝愿您的心愿早日达成！') </script>";
				//header('location:/?ac=index');
			}
	        $tpl     = 'yice/xydd_ck.tpl';
	        $content = tpl::fetch($tpl);
	        exit($content);
	    }
	
	//独立剥离我的许愿板块 MH20201117	
	
	public function xydd_self(){
						
			//cookies记录的历史许愿
			$orders= mod_order::get_history();
			foreach($orders as $k=>$v){
			    $orders_arr = db::queryone("select * from `ffsm_orders` where oid='".$v."' and `type` = 21 ORDER BY `id` DESC");
			    
				
				
				if($orders_arr[oid]!=""){
			        //$orders_arr['data'] = json_decode(urldecode($orders_arr['data']),true);
			        $history_data[$k] = $orders_arr;
					
					$img = db::queryone("select title,img from `yice_deng` where id='".$orders_arr['lantern_id']."' ORDER BY `id` DESC");
					
					if ($history_data[$k]['status']==0){
						$history_data[$k]['status']="普通";
					}else{
						$history_data[$k]['status']="加亮";
					}
					
					if ($history_data[$k]['shen']==0){
						$history_data[$k]['shen']="待审";
					}elseif ($history_data[$k]['shen']==1){
						$history_data[$k]['shen']="已审";
					}else{
						$history_data[$k]['shen']="隐藏";
					}
					
					$history_data[$k]['lantern_id'] = $img['title'];
					$history_data[$k]['lantern_img'] = $img['img'];
					$history_data[$k]['url'] = "/?ac=index&oid=".$orders_arr['oid']."&token=".base64_encode(md5($orders_arr[oid]));
			    }
				
			}
						
			tpl::assign('history_data',$history_data);
	        $tpl     = 'yice/xydd_my.tpl';
			
			$content = tpl::fetch($tpl);
			exit($content);
	    }
		
	//独立剥离许愿广场 MH20201117
	
	public function xydd_gc(){
			
			//调取提交的许愿
			
			$xydd_all=db::fetch_all(db::query('SELECT * FROM `ffsm_orders` WHERE `shen` = 1 AND `type` = 21 AND `qfshow` = 1 ORDER BY `id` DESC limit 0,20'));
			foreach($xydd_all as $k=>$v){
				$img = db::queryone("select img from `yice_deng` where id='".$v['lantern_id']."' ORDER BY `id` DESC");
				$xydd_all[$k]['lantern_img'] = $img['img'];
			}
			
			
			$xydd_mall=db::fetch_all(db::query('SELECT * FROM `ffsm_orders` WHERE `shen` = 1 AND `type` = 21 AND `qfshow` = 1 ORDER BY `qfdj` DESC limit 0,20'));
			foreach($xydd_mall as $k=>$v){
				$img = db::queryone("select img from `yice_deng` where id='".$v['lantern_id']."' ORDER BY `id` DESC");
				$xydd_mall[$k]['lantern_img'] = $img['img'];
			}
			
			
			$xydd_weekall=db::fetch_all(db::query('SELECT * FROM `ffsm_orders` WHERE week(from_unixtime(`createtime`))=week(now())   and YEAR(from_unixtime(`createtime`))=YEAR(now()) and `shen` = 1 AND `type` = 21 AND `qfshow` = 1 ORDER BY `qfdj` DESC limit 0,20'));
			foreach($xydd_weekall as $k=>$v){
				$img = db::queryone("select img from `yice_deng` where id='".$v['lantern_id']."' ORDER BY `id` DESC");
				$xydd_weekall[$k]['lantern_img'] = $img['img'];
			}
									
			tpl::assign('xydd_all',$xydd_all);
			tpl::assign('xydd_weekall',$xydd_weekall);
			tpl::assign('xydd_mall',$xydd_mall);
			
	        $tpl     = 'yice/xydd_gc.tpl';
			
			$content = tpl::fetch($tpl);
			exit($content);
	    }
	
    public function autowrap($fontsize, $angle, $fontface, $string, $width) {
        $content = "";
        for ($i=0;$i<mb_strlen($string);$i++) {
            $letter[] = mb_substr($string, $i, 1);
        }
        foreach ($letter as $l) {
            $teststr = $content." ".$l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            if ((($testbox[2]-$testbox[0]) > $width) && ($content !== "")) {
                $content .= "\n\n";
            }
            $content .= $l;
        }
        return $content;
    }
    public function xydd_img($dst,$src_path,$text,$text1 ){
        mb_internal_encoding("UTF-8");
        $img = imagecreatefromstring(file_get_contents($dst));
        $src = imagecreatefromstring(file_get_contents($src_path));
        $width = 400;
        $height = 400;
        $white = imagecolorallocate($img, 255, 255, 255);
        $fontfile = './ffsm/statics/ffsm/xydd/mnjkt.ttf';
        $text_len =  mb_strwidth($text)/2;// 这是中文字符的个数
        $x = sqrt($text_len);//获得一个初始的字数安排
        $px = ceil($width / (2*$x));// 获得一个初始的像素
        $fontsize = 10;//获得一个初始的字体磅值
        $a = $this->autowrap($fontsize,0,$fontfile,$text,$width);
        $text_change = $a;
        $text_fontBox = imagettfbbox($fontsize, 0, $fontfile, $text_change);
        $text_height = $text_fontBox[1]-$text_fontBox[7];
        $text_width = $text_fontBox[2]-$text_fontBox[0];
        while ($text_height > $height  || $text_height < ($height -round($fontsize*96/72)*1.8)) {
            if ($text_height > $height ) {
                $fontsize = $fontsize-1;
            }elseif ($text_height < ($height -round($fontsize*96/72)*1.8)) {
                $fontsize = $fontsize+1;
            }
            $a =  $this->autowrap($fontsize,0,$fontfile,$text,$width);
            $text_fontBox = imagettfbbox($fontsize, 0, $fontfile, $text_change);
            $text_height =$text_fontBox[1]-$text_fontBox[7];
            $text_width = $text_fontBox[2]-$text_fontBox[0];
        }
        $text_width = $text_fontBox[2]-$text_fontBox[0];
        if ($text_width >$width || $width-$text_width >$fontsize*96/72*1.2) {
            $fontsize = $fontsize - 2;
        }
        imagettftext($img, 16, 0,20, 60, $white, $fontfile, $text_change);
        imagettftext($img, 16, 0, 280, 280, $white, $fontfile, $text1);
        list($src_w, $src_h) = getimagesize($src_path);
        $newwidth = 196;
        $newheight = 243;
        // Load
        $thumb = imagecreate($newwidth, $newheight);
        imagecopyresized($thumb, $src, 0, 0, 0, 0, $newwidth, $newheight, $src_w, $src_h);
        imagecopy($img, $thumb, 180, 397, 0, 0, 196, 243);
        $name = time().rand(0,1000);
        imagejpeg($img,'./ffsm/xydd/'.$name.'.jpg');
        return $name.'.jpg';
    }
    public function splitName($fullname){
        $hyphenated = array('欧阳','太史','端木','上官','司马','东方','独孤','南宫','万俟','闻人','夏侯','诸葛','尉迟','公羊','赫连','澹台','皇甫',
            '宗政','濮阳','公冶','太叔','申屠','公孙','慕容','仲孙','钟离','长孙','宇文','城池','司徒','鲜于','司空','汝嫣','闾丘','子车','亓官',
            '司寇','巫马','公西','颛孙','壤驷','公良','漆雕','乐正','宰父','谷梁','拓跋','夹谷','轩辕','令狐','段干','百里','呼延','东郭','南门',
            '羊舌','微生','公户','公玉','公仪','梁丘','公仲','公上','公门','公山','公坚','左丘','公伯','西门','公祖','第五','公乘','贯丘','公皙',
            '南荣','东里','东宫','仲长','子书','子桑','即墨','达奚','褚师');
        $vLength = mb_strlen($fullname, 'utf-8');
        $lastname = '';
        $firstname = '';//前为姓,后为名
        if($vLength > 2){
            $preTwoWords = mb_substr($fullname, 0, 2, 'utf-8');//取命名的前两个字,看是否在复姓库中
            if(in_array($preTwoWords, $hyphenated)){
                $lastname = $preTwoWords;
                $firstname = mb_substr($fullname, 2, 10, 'utf-8');
            }else{
                $lastname = mb_substr($fullname, 0, 1, 'utf-8');
                $firstname = mb_substr($fullname, 1, 10, 'utf-8');
            }
        }else if($vLength == 2){//全名只有两个字时,以前一个为姓,后一下为名
            $lastname = mb_substr($fullname ,0, 1, 'utf-8');
            $firstname = mb_substr($fullname, 1, 10, 'utf-8');
        }else{
            $lastname = $fullname;
        }
        return array($lastname, $firstname);
    }
    private function public_sm($cookies){
        $jmsh['jin'] = mod_suanming::howstring($cookies['wh'],'金');
        $jmsh['mu'] = mod_suanming::howstring($cookies['wh'],'木');
        $jmsh['shui'] = mod_suanming::howstring($cookies['wh'],'水');
        $jmsh['huo'] = mod_suanming::howstring($cookies['wh'],'火');
        $jmsh['tu'] = mod_suanming::howstring($cookies['wh'],'土');
        $wharr = mod_suanming::whwq($jmsh['jin'],$jmsh['mu'],$jmsh['shui'],$jmsh['huo'],$jmsh['tu']);
        //同类异类五行
        $sql="select * from `sm_wh` where wh='".$cookies['wh'][4]."'";
        $tywh = db::queryone($sql);
        //纳音
        $sql='select * from `sm_jiazi` where jiazi="'.$cookies['bazi'][0].$cookies['bazi'][1].'"';
        $nayin[]=db::queryone($sql);
        $sql2='select * from `sm_jiazi` where jiazi="'.$cookies['bazi'][2].$cookies['bazi'][3].'"';
        $nayin[]=db::queryone($sql2);
        $sql3='select * from `sm_jiazi` where jiazi="'.$cookies['bazi'][4].$cookies['bazi'][5].'"';
        $nayin[]=db::queryone($sql3);
        $sql4='select * from `sm_jiazi` where jiazi="'.$cookies['bazi'][6].$cookies['bazi'][7].'"';
        $nayin[]=db::queryone($sql4);
        //生肖个性
        $sql="select * from `sm_sxgx` where sx='".$cookies['sx']."'";
        $sxgx=db::queryone($sql);
        //节气
        $solarTerm =array("小寒","大寒 ","立春","雨水 ","惊蛰","春分 ","清明","谷雨 ","立夏","小满 ","芒种","夏至 ","小暑","大暑 ","立秋","处暑 ","白露","秋分 ","寒露","霜降 ","立冬","小雪 ","大雪","冬至 ");
        eregi("(.*)/(.*)", $cookies['jieqi']['term1'],$zc_1);
        $zc1 = $solarTerm[$zc_1[1]].$zc_1[2];
        eregi("(.*)/(.*)", $cookies['jieqi']['term2'], $zc_2);
        $zc2 = $solarTerm[$zc_2[1]].$zc_2[2];
        $info['jmsh'] = $jmsh;
        $info['wharr'] = $wharr;
        $info['tywh'] = $tywh;
        $info['nayin'] = $nayin;
        $info['sxgx'] = $sxgx;
        return $info;
    }
  //我的测算
  public function user_wdcs(){
        $tpl     = 'yice/user_wdcs.tpl';
        $content = tpl::fetch($tpl);
        exit($content);		
    }
    public function user_wdcs_find(){
	    $transaction_id = req::item('transaction_id');
        $tx_query="SELECT * FROM `ffsm_orders` WHERE `transaction_id` = '".$transaction_id."' ORDER BY `createtime` DESC";
        $infos = db::get_one($tx_query);
        $infos['url'] = $this->cache_prefix.'/?ac=index&oid='.$infos['oid'].'&token='.base64_encode(md5($infos['oid'])).'';
        tpl::assign('infos',$infos);
        $tpl     = 'yice/user_wdcs_find.tpl';
        $content = tpl::fetch($tpl);
        exit($content);
    }

    public function returnback(){
        $out_trade_no = req::item('out_trade_no');
        $token = req::item('token');
        if(base64_encode(md5($out_trade_no)) == $token){
            require_once 'api.php';
            $mchid = YZF_PARTNER;
            $private_key = YZF_KEY;
            $data=array(
                'mchid'     	=> $mchid,
                'out_trade_no'  => $out_trade_no,
                'nonce_str' 	=> str_shuffle(time()),
            );
            sleep(5);//延迟5秒在请求
            $url = 'https://admin.xunhuweb.com/pay/query';
            $data['sign']	  = XH_Payment_Api::generate_xh_hash($data,$private_key);
            $response   	  = XH_Payment_Api::http_post_json($url, json_encode($data));
            $result     	  = $response?json_decode($response,true):null;
            if(isset($result['status'])&&$result['status']=='complete'){
                $url = $this->cache_prefix.'/?ac=index&oid='.$out_trade_no.'&token='.base64_encode(md5($out_trade_no)).'';
                header("location:".$url."");
                exit();
            }else{
                echo 'fail';
            }
        }else{
            die('验证错误！');
        }
    }

    public function notify(){
        require_once 'api.php';
        $mchid = YZF_PARTNER;
        $private_key = YZF_KEY;
        $data=(array)json_decode(file_get_contents('php://input'));
        if(!$data){
            exit('faild!');
        }
        $out_trade_no = isset($data['out_trade_no'])?$data['out_trade_no']:null;
        $order_id=isset($data['order_id'])?$data['order_id']:null;
        $hash =XH_Payment_Api::generate_xh_hash($data,$private_key);
        if($data['sign']!=$hash){
            //签名验证失败
            echo '签名错误';exit;
        }
        if($data['status']=='complete'){
            file_put_contents("log2.txt",json_encode($data)."\r\n",FILE_APPEND);
            mod_order::up_order(array('paytype'=>1,'status'=>1,'paytime'=>$data['time_end'],'transaction_id'=>$data['transaction_id'],'order_id'=>$data['order_id'],'total_fee'=>($data['total_fee']/100)), " `oid`='".$out_trade_no."'");
        }else{
            //处理未支付的情况
        }
        //以下是处理成功后输出，当支付平台接收到此消息后，将不再重复回调当前接口
        print 'success';
        exit;

    }



}